﻿using System;
using System.Configuration;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using mojoPortal.Web.RS.CRM.AppCode.Lib;


namespace mojoPortal.Web.RS.CRM.Controls
{
    public partial class ModalAccountOrderControl : RSBaseUserControl
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                RSUserIdentity userIdentity = GetRSUserIdentity(); //new RSUserIdentity();
                RSCRMDataLookupLoader.LoadProviderDDL(userIdentity.RSCompanyId, ddlProvider, "< Please Select Provider>", "0");
            }
        }

        public void ShowModal(int companyid, string accountid)
        {
            hfIsDirty.Value = "";
            LoadList(companyid, accountid);
            mpeModalManage.Show();
        }

        protected void btnModalOK_Click(Object sender, EventArgs e)
        {
            mpeModalManage.Hide();
            if (hfIsDirty.Value == "1")
            {
                var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
                nameValues.Set("selindex", "1");
                string updatedQueryString = "?" + nameValues.ToString();
                string url = Request.Url.AbsolutePath;
                url = url + updatedQueryString;
                Response.Redirect(url);
            }
        }

        protected void lnkDelete_Click(object sender, CommandEventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            string accountid = lblAccountID.Text;
            int AccountOrderID = Convert.ToInt32(e.CommandArgument.ToString());
            Delete(accountid, AccountOrderID, userIdentity.RSCompanyId);
            LoadList(userIdentity.RSCompanyId, accountid);
            hfIsDirty.Value = "1";
        }

        protected void btnSave_Click(object sender, CommandEventArgs e)
        {
            if (gvAccountOrder.SelectedIndex >= 0)
            {
                UpdateAccountOrder();
                //SetControlState(false);
                //gvAccountOrder.SelectedIndex = -1;
            }
        }
        protected void btnCancel_Click(object sender, CommandEventArgs e)
        {
            if (gvAccountOrder.SelectedIndex >= 0)
            {
                SetControlState(false);
                gvAccountOrder.SelectedIndex = -1;
            }
        }
        protected void gv_SelectedIndexChanged(Object sender, EventArgs e)
        {
            if (gvAccountOrder.SelectedIndex >= 0)
            {
                SetControlState(true);
            }
        }

        protected void gv_SelectedIndexChanging(Object sender, EventArgs e)
        {
            if (gvAccountOrder.SelectedIndex >= 0)
            {
                SetControlState(false);
            }
        }
        private void SetControlState(bool bstate)
        {
            if (gvAccountOrder.SelectedIndex >= 0)
            {
                Button btnSave = gvAccountOrder.SelectedRow.FindControl("btnSave") as Button;
                if (btnSave != null)
                    btnSave.Visible = bstate;

                Button btnCancel = gvAccountOrder.SelectedRow.FindControl("btnCancel") as Button;
                if (btnCancel != null)
                    btnCancel.Visible = bstate;

                LinkButton lnkDelete = gvAccountOrder.SelectedRow.FindControl("lnkDelete") as LinkButton;
                if (lnkDelete != null)
                    lnkDelete.Visible = !bstate;

                //edit mode
                TextBox txtContractNumber = gvAccountOrder.SelectedRow.FindControl("txtContractNumber") as TextBox;
                if (txtContractNumber != null)
                    txtContractNumber.Visible = bstate;
                TextBox txtDeliveryDate = gvAccountOrder.SelectedRow.FindControl("txtDeliveryDate") as TextBox;
                if (txtDeliveryDate != null)
                    txtDeliveryDate.Visible = bstate;
                TextBox txtApplicationDate = gvAccountOrder.SelectedRow.FindControl("txtApplicationDate") as TextBox;
                if (txtApplicationDate != null)
                    txtApplicationDate.Visible = bstate;
                TextBox txtIssueDate = gvAccountOrder.SelectedRow.FindControl("txtIssueDate") as TextBox;
                if (txtIssueDate != null)
                    txtIssueDate.Visible = bstate;

                //readonly mode
                Label lblContractNumber = gvAccountOrder.SelectedRow.FindControl("lblContractNumber") as Label;
                if (lblContractNumber != null)
                    lblContractNumber.Visible = !bstate;
                Label lblDeliveryDate = gvAccountOrder.SelectedRow.FindControl("lblDeliveryDate") as Label;
                if (lblDeliveryDate != null)
                    lblDeliveryDate.Visible = !bstate;
                Label lblApplicationDate = gvAccountOrder.SelectedRow.FindControl("lblApplicationDate") as Label;
                if (lblApplicationDate != null)
                    lblApplicationDate.Visible = !bstate;
                Label lblIssueDate = gvAccountOrder.SelectedRow.FindControl("lblIssueDate") as Label;
                if (lblIssueDate != null)
                    lblIssueDate.Visible = !bstate;

                Label lblIsQualified = gvAccountOrder.SelectedRow.FindControl("lblIsQualified") as Label;
                if (lblIsQualified != null)
                {
                    lblIsQualified.Visible = !bstate;
                    DropDownList ddlIsQualified = gvAccountOrder.SelectedRow.FindControl("ddlIsQualified") as DropDownList;
                    if (ddlIsQualified != null)
                    {
                        ddlIsQualified.Visible = bstate;
                        ddlIsQualified.SelectedValue = lblIsQualified.Text;
                    }
                }
            }
        }
        private void UpdateAccountOrder()
        {
            if (gvAccountOrder.SelectedIndex >= 0)
            {
                RSUserIdentity userIdentity = GetRSUserIdentity();
                string isqualified = string.Empty;
                string contractnum = string.Empty;
                string deliverydate = string.Empty;
                string applicationdate = string.Empty;
                string issuedate = string.Empty;

                int accountorderid = Convert.ToInt32(gvAccountOrder.DataKeys[gvAccountOrder.SelectedIndex].Value);

                TextBox txtContractNumber = gvAccountOrder.SelectedRow.FindControl("txtContractNumber") as TextBox;
                if (txtContractNumber != null)
                    contractnum = txtContractNumber.Text;
                TextBox txtDeliveryDate = gvAccountOrder.SelectedRow.FindControl("txtDeliveryDate") as TextBox;
                if (txtDeliveryDate != null)
                    deliverydate = txtDeliveryDate.Text;
                TextBox txtApplicationDate = gvAccountOrder.SelectedRow.FindControl("txtApplicationDate") as TextBox;
                if (txtApplicationDate != null)
                    applicationdate = txtApplicationDate.Text;
                TextBox txtIssueDate = gvAccountOrder.SelectedRow.FindControl("txtIssueDate") as TextBox;
                if (txtIssueDate != null)
                    issuedate = txtIssueDate.Text;
                DropDownList ddlIsQualified = gvAccountOrder.SelectedRow.FindControl("ddlIsQualified") as DropDownList;
                if (ddlIsQualified != null)
                    isqualified = ddlIsQualified.SelectedValue;

                Update(accountorderid, userIdentity.RSCompanyId, userIdentity.RSCurrentUser, contractnum, isqualified, deliverydate, applicationdate, issuedate);
                LoadList(userIdentity.RSCompanyId, lblAccountID.Text);
                hfIsDirty.Value = "1";
            }
        }
        
        protected void btnAddProduct_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            string accountid = lblAccountID.Text;
            int providerid = Convert.ToInt32(ddlProvider.SelectedValue.ToString());
            int productid = 0;
            for (int i = 0; i < chkProduct.Items.Count; i++)
            {
                if (chkProduct.Items[i].Selected)
                {
                    productid = Convert.ToInt32(chkProduct.Items[i].Value.ToString());
                    if (accountid != null && providerid > 0 && productid > 0)
                    {
                        Save(accountid, providerid, productid, userIdentity.RSCompanyId, userIdentity.RSCurrentUser);
                    }
                }
            }
            LoadList(userIdentity.RSCompanyId, accountid);
            hfIsDirty.Value = "1";
            btnAddProduct.Enabled = false;
        }
        private void Delete(string accountid, int AccountOrderID, int companyid)
        {
            string SQL = "DELETE FROM rs_tblAccountOrder WHERE AccountID=@accountid AND AccountOrderID=@AccountOrderID AND CompanyID=@companyid";
            SqlCommand sqlCmd = new SqlCommand();

            SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@accountid", SqlDbType.NVarChar, 15, ParameterDirection.Input, accountid);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@AccountOrderID", SqlDbType.Int, 0, ParameterDirection.Input, AccountOrderID);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, companyid);
            SQLHelper.SetCommandType(sqlCmd, CommandType.Text, SQL);
            SQLHelper.ExecuteScalarCmd(sqlCmd);
            int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
        }
        private void Save(string accountid, int providerid, int productid, int companyid, string currentuser)
        {
            string SQL = "INSERT INTO rs_tblAccountOrder(AccountID, ProductID, CompanyID, Audit_CreateBy, Audit_CreateDt) VALUES(@accountid, @productid, @companyid, @currentuser, GETDATE())";
            SqlCommand sqlCmd = new SqlCommand();

            SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@currentuser", SqlDbType.NVarChar, 25, ParameterDirection.Input, currentuser);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@accountid", SqlDbType.NVarChar, 15, ParameterDirection.Input, accountid);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@productid", SqlDbType.Int, 0, ParameterDirection.Input, productid);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@providerid", SqlDbType.Int, 0, ParameterDirection.Input, providerid);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, companyid);
            SQLHelper.SetCommandType(sqlCmd, CommandType.Text, SQL);
            SQLHelper.ExecuteScalarCmd(sqlCmd);
            int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
        }
        private void Update(int accountorderid, int companyid, string currentuser, string contractnum, string isqualified, string deliverydate, string applicationdate, string issuedate)
        {
            string SQL = "UPDATE rs_tblAccountOrder SET ContractNum=@contractnum, IsQualified=@isqualified, DeliveryDate=@deliverydate, ApplicationDate=@applicationdate, IssueDate=@issuedate, Audit_UpdateBy=@currentuser, Audit_UpdateDt=GETDATE() WHERE AccountOrderId=@accountorderid AND CompanyId=@companyid";
            SqlCommand sqlCmd = new SqlCommand();

            SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@currentuser", SqlDbType.NVarChar, 25, ParameterDirection.Input, currentuser);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@accountorderid", SqlDbType.Int, 0, ParameterDirection.Input, accountorderid);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@companyid", SqlDbType.Int, 0, ParameterDirection.Input, companyid);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@contractnum", SqlDbType.NVarChar, 15, ParameterDirection.Input, contractnum);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@isqualified", SqlDbType.NVarChar, 6, ParameterDirection.Input, isqualified);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@deliverydate", SqlDbType.DateTime, 0, ParameterDirection.Input, deliverydate);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@applicationdate", SqlDbType.DateTime, 0, ParameterDirection.Input, applicationdate);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@issuedate", SqlDbType.DateTime, 0, ParameterDirection.Input, issuedate);

            SQLHelper.SetCommandType(sqlCmd, CommandType.Text, SQL);
            SQLHelper.ExecuteScalarCmd(sqlCmd);
            int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
        }
        protected void ddlProvider_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            int providerid = Convert.ToInt32(ddlProvider.SelectedValue.ToString());
            if (providerid > 0)
            {
                RSUserIdentity userIdentity = GetRSUserIdentity(); //new RSUserIdentity();
                RSCRMDataLookupLoader.LoadProductByProviderID(userIdentity.RSCompanyId, providerid, chkProduct);
                btnAddProduct.Visible = true;
            }
        }

        public bool LoadList(int companyid, string accountid)
        {
            bool bHasValue = false;
            //LoadIsQualifiedDDL();

            if (companyid > 0 && accountid != null)
            {
                lblAccountID.Text = accountid;
                SqlCommand myCommand;
                SqlParameter param;
                SqlConnection myConnection;
                String sqlSELECT = "SELECT c.AccountOrderID, c.AccountID, c.ProductID, c.ContractNum, ISNULL(c.IsQualified, '') as IsQualified, c.DeliveryDate, c.ApplicationDate, c.IssueDate, d.productname, v.providername FROM [dbo].[rs_tblAccountOrder] c INNER JOIN rs_tblProduct d ON c.productid=d.productid INNER JOIN rs_tblProvider v ON d.providerid=v.providerid WHERE c.AccountID=@accountid AND c.CompanyID=@companyid";

                myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
                myCommand = new SqlCommand(sqlSELECT, myConnection);

                param = new SqlParameter();
                param.SqlDbType = SqlDbType.Int;
                param.ParameterName = "@companyid";
                param.Value = companyid;
                myCommand.Parameters.Add(param);

                param = new SqlParameter();
                param.SqlDbType = SqlDbType.NVarChar;
                param.ParameterName = "@accountid";
                param.Value = accountid;
                myCommand.Parameters.Add(param);

                SqlDataAdapter adapter = new SqlDataAdapter(myCommand);
                myConnection.Open();
                DataSet ds = new DataSet();
                adapter.Fill(ds);

                gvAccountOrder.DataSource = ds;
                gvAccountOrder.DataBind();
                myConnection.Close();

                if (gvAccountOrder.Rows.Count > 0)
                {
                    bHasValue = true;
                }
            }
            return bHasValue;
        }

    }

}